package org.shijiagen.handler;

import org.shijiagen.utils.R;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.Optional;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R defaultErrorHandler(Exception e){
        e.printStackTrace();
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        return R.fail(Optional.ofNullable(e.getBindingResult().getFieldError()).orElse(new FieldError(e.getObjectName(), Arrays.toString(e.getSuppressedFields()),"字段验证异常")).getDefaultMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R httpRequestMethodNotSupportedException(){
        return R.fail("请求方法错误！");
    }

    @ExceptionHandler(IllegalStateException.class)
    public R illegalStateException(IllegalStateException e){
        return R.fail(e.getMessage());
    }
}
